<?php
/**
 * Hols class Image_GetBlockFactory
 *
 * @author daantimmer
 *
 * @package Library
 * @subpackage Image
 */

/**
 * A simple callback class used to interface with a Image_Image.
 *
 * This callback factory returns a single color, defined by a blocksize.
 *
 * @see Image_Image
 * @author daantimmer
 */
class Image_GetBlockFactory{

	/**
	 * @var string
	 */
	private $callback;
	
	/**
	 * Constructor
	 *
	 * @param string $callback
	 * @return void
	 */
	public function __construct($callback){
		$callback = "get{$callback}";
		if(method_exists($this,$callback))
				$this->callback = $callback;
		else	throw new Excpetion("callback ({$callback}) not found");
	}
	
	/**
	 * Uses $callback (set by constructor) to make a virtual callback
	 *
	 * @param integer $xs
	 * @param integer $ys
	 * @param integer $blocksize
	 * @param Image_Image $img
	 * @return Image_Lib_Color
	 */
	public function get($xs,$ys,$blocksize, $img){
		return $this->{$this->callback}($xs,$ys,$blocksize,$img);
	}
	
	/**
	 * @var integer
	 */
	private static $bucketsize = 200;
	
	/**
	 * @var integer
	 */
	private static $bucketpercent = 10;
	
	/**
	 * @var integer
	 */
	private static $bmax = 20;
	
	/**
	 * @var integer
	 */
	private static $bmin = -20;
	
	/**
	 * @var integer[]
	 */
	private $bucket = array();
	
	private function getH($xs,$ys,$blocksize,$img){
		$this->bucket = array();
		$mw = min($xs+$blocksize, $img->getWidth());
		$mh = min($ys+$blocksize, $img->getHeight());
		
		$avgS = $avgV = 0;
		
		$highindex = $highvalue = $value = $newval = $changecount = 0;
		
		for($y = $ys, $yn = $mh; $y < $yn; $y++){
			for($x = $xs, $xn = $mw; $x < $xn; $x++){
				$value = floor($img->getH($x,$y) * self::$bucketsize);
				
//				$newval = $highindex - $value;
				
				if(isset($this->bucket[$value]))
						$this->bucket[$value]++;
				else	$this->bucket[$value] = 1;
				
				if($this->bucket[$value] > $highvalue){
					$highvalue = $this->bucket[$highindex = $value];
					
					$avgS += $img->getS($x,$y);
					$avgV += $img->getV($x,$y);
					$changecount++;
				}
			}
		}
		
//		$div = ($mw - $xs) * ($mh - $ys);
		$avgS /= $changecount;
		$avgV /= $changecount;
		$h = $highindex/self::$bucketsize;
		return new Image_Lib_Color(Image_Lib_Color::hsv2rgb(array($h,$avgS,$avgV)));
	}
}